package weaver.interfaces.hggd.zjs.Util;

import biweekly.util.org.apache.commons.codec.binary.Base64;
import okhttp3.*;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

public class AMSUtil {
    private static final String URl = "http://200.162.8.193:8088/ams/wsDataFilling";
    /**
     * 通过用户名密码拼接auth编码
     * @param userName
     * @param password
     * @return
     */
    public static String getBaseAuth(String userName, String password) {
        String auth = userName + ":" + password;
        String encode = (new Base64()).encodeToString(auth.getBytes(Charset.forName("UTF-8")));
        return "Basic " + encode;
    }

    /**
     * 调用接口 Post请求
     *
     * @param bodeStr
     * @return
     * @throws IOException
     */
    public static String send(String bodeStr) throws IOException {
        try {
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(60, TimeUnit.SECONDS)//设置连接超时时间
                    .readTimeout(60, TimeUnit.SECONDS)//设置读取超时时间
                    .readTimeout(60, TimeUnit.SECONDS)
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, bodeStr);
            Request request = new Request.Builder()
                    .url(URl )
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            return result;
        } catch (Exception e) {
            new BaseBean().writeLog("请求超时" + e);
            return "0";
        }
    }
    /**
     * 通过传的字段值查询 字段名
     * @param tablename
     * @param queryName
     * @param id
     * @param value
     * @return
     */
    public static String getNameByid(String tablename, String queryName, String id, String value) {
        if ("".equals(value)) {
            return "";
        }
        RecordSet rs = new RecordSet();
        rs.executeQuery("select " + queryName + " from " + tablename + " where " + id + "=?", value);
        if (rs.next()) {
            return weaver.general.Util.null2String(rs.getString(queryName));
        }
        return "";
    }

}
